package com.umeox.watch.moto.launcher.fragment;

import static com.umeox.watch.moto.launcher.event.DeviceStatusChangedEvent.BIND;
import static com.umeox.watch.moto.launcher.event.DeviceStatusChangedEvent.UNBOUND;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.LayoutDirection;
import android.view.View;

import androidx.core.text.TextUtilsCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.app.ThemeFragment;
import com.umeox.moto.watch.themes.widget.TextView;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.adapter.AppGroupListAdapter;
import com.umeox.watch.moto.launcher.bean.AppGroupInfo;
import com.umeox.watch.moto.launcher.constant.Constant;
import com.umeox.watch.moto.launcher.event.DeviceStatusChangedEvent;
import com.umeox.watch.moto.launcher.ui.MainActivity;
import com.umeox.watch.moto.launcher.ui.SecondaryMenuActivity;
import com.umeox.watch.moto.launcher.ui.help.AppListScaleTransformer;
import com.umeox.watch.moto.launcher.ui.help.GalleryLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;


/**
 * Created by Rambo 2019-07-04
 * Describe:
 */
public class AppListFragment extends ThemeFragment implements AppGroupListAdapter.OnClickListener {

    public RecyclerView mAppListView;

    private static AppListFragment INSTANCE;

    private AppGroupListAdapter adapter;

    private TextView mCurrentAppNameTv;

    private boolean mVisible;

    private GalleryLayoutManager galleryLayoutManager;

    private ArrayList<AppGroupInfo> appGroupInfoList = new ArrayList<>();

    private final ContentObserver qimiObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onChange(boolean selfChange) {
            Logger.d("设备配置信息发生修改 isActivated = " + DataProvider.isActivated());
            if (DataProvider.isActivated()) {
                AppListConfigureInfo.INSTANCE.updateBindStatusAppGroupList();
                adapter.notifyDataSetChanged();
            }
        }
    };

    public AppListFragment() {
        INSTANCE = this;
    }

    public static AppListFragment getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new AppListFragment();
            final Bundle bundle = new Bundle();
            bundle.putBoolean(Constant.KEY_CLEAR_FRAGMENT, true);
            INSTANCE.setArguments(bundle);
        }
        return INSTANCE;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
        try {
            Objects.requireNonNull(getActivity()).getContentResolver().unregisterContentObserver(qimiObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        mVisible = true;
        Logger.e("==============onResume==================");
        if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == LayoutDirection.RTL) {
            ((MainActivity) requireActivity()).setPagingEnabled(adapter.getItemCount() - 1 == galleryLayoutManager.getCurSelectedPosition());
        } else {
            ((MainActivity) requireActivity()).setPagingEnabled(0 == galleryLayoutManager.getCurSelectedPosition());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Logger.e("==============onPause==================");
        mVisible = false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_applist;
    }

    @Override
    protected void initView(View rootView) {
        Logger.e("AppListFragment initView");
        AppListConfigureInfo.INSTANCE.initAppInfo();
        mAppListView = rootView.findViewById(R.id.app_list_view);
        mCurrentAppNameTv = rootView.findViewById(R.id.app_name_tv);
        initData(DataProvider.isActivated());
    }

    public void initData(boolean isBind) {
        Logger.e("AppListFragment initData,device isActivated=" + DataProvider.isActivated());
        appGroupInfoList = AppListConfigureInfo.INSTANCE.getAppGroupList(isBind);
        adapter = new AppGroupListAdapter(getContext(), appGroupInfoList);
        mAppListView.setAdapter(adapter);
        adapter.setOnClickListener(this);
        mAppListView.setHasFixedSize(true);

        galleryLayoutManager = new GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL);
        galleryLayoutManager.setItemTransformer(new AppListScaleTransformer());
        galleryLayoutManager.attach(mAppListView);
//        mAppListView.smoothScrollToPosition(1);

        galleryLayoutManager.setOnItemSelectedListener((recyclerView, item, position) -> {
            mCurrentAppNameTv.setText(appGroupInfoList.get(position).appLabel);
            Logger.e("galleryLayoutManager.position()=" + position);
            if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == LayoutDirection.RTL) {
                ((MainActivity) requireActivity()).setPagingEnabled(adapter.getItemCount() - 1 == position);
            } else {
                ((MainActivity) requireActivity()).setPagingEnabled(0 == position);
            }

            Logger.e("isUserInputEnabled=" + ((MainActivity) requireActivity()).isUserInputEnabled());

        });

        DataProvider.DeviceConfigProvider.registerContentObserver(false, qimiObserver);

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onDeviceStatusChangedEvent(DeviceStatusChangedEvent event) {
        Logger.e("AppListFragment onDeviceStatusChangedEvent,event.mDeviceStatus=" + event.mDeviceStatus);
        if (event.mDeviceStatus == UNBOUND) {
            initData(false);
        } else if (event.mDeviceStatus == BIND) {
            initData(true);
        }
        Logger.e("AppListFragment mAppInfoList.size=" + appGroupInfoList.size());
//        adapter.setData(mAppInfoList);
//        mAppListView.setAdapter(adapter);

    }


    @Override
    public void onPositionClick(int position) {
        if (!mVisible) {
            return;
        }
        AppGroupInfo group = appGroupInfoList.get(position);
        if (group.canDirectHandleAppAction()) {
            assert group.appInfos != null;
            AppListConfigureInfo.handleAppAction(group.appInfos.get(0), mContext);
        } else {
            //进入二级页面
            SecondaryMenuActivity.launch(mContext, position);
        }
    }
}
